package com.trimer.rpc.core.controller;

import com.trimer.rpc.core.RpcHandler;
import com.trimer.rpc.core.request.RpcRequest;
import com.trimer.rpc.core.response.RpcResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value="/rpc")
public class RpcController {

    @Autowired
    private RpcHandler rpcHandler;

    @RequestMapping(value="/invoke",method= RequestMethod.POST)
    public ResponseEntity<RpcResponse> invokeRpc(@RequestBody RpcRequest request) {
        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setSid(request.getSid());

        //获取对象,调用具体的对象
        try {
            Object object = rpcHandler.handle(request);
            rpcResponse.setResult(object);
        } catch (Exception e) {
            rpcResponse.setException(e);
        }

        return new ResponseEntity<>(rpcResponse, HttpStatus.OK);
    }
}